﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using SilverlightSdms.AdminService;
using System.Text.RegularExpressions;
using SilverlightSdms.Common;

namespace SilverlightSdms.Views
{

    public partial class Administrator : Page
    {
        public User User { get; set; }

        public ObservableCollection<User> AllUsers { get; set; }

        public ObservableCollection<User> AllTeamMembers { get; set; }

        public ObservableCollection<School> AllSchools { get; set; }

        public ObservableCollection<Region> AllSchoolRegions { get; set; }

        public ObservableCollection<Team> AllTeams { get; set; }

        public School School { get; set; }

        public Team Team { get; set; }

        public Region SchoolRegion { get; set; }

        public Region TeamRegion { get; set; }

        public ObservableCollection<Role> Roles { get; set; }

        private readonly UsersServiceClient _adminService = new UsersServiceClient();

        private ObservableCollection<Role> AllRoles { get; set; }

        public Administrator()
        {

            InitializeComponent();
            this.User = new User();
            this.Roles = new ObservableCollection<Role>();
            this.AllRoles = new ObservableCollection<Role>();
            AllTeams = new ObservableCollection<Team>();
            AllSchools = new ObservableCollection<School>();
            AllSchoolRegions= new ObservableCollection<Region>();
            AllUsers = new ObservableCollection<User>();
            AllTeamMembers = new ObservableCollection<User>();
            School = new School();
            this.gridAddUser.DataContext = User;
            grid2.DataContext = School;
            this.comboBoxSchoolRegionName.ItemsSource = AllSchoolRegions;
            this.listBoxSchools.ItemsSource = AllSchools;
            this.listBoxTeams.ItemsSource = AllTeams;

            #region Handle Teams

            listBoxTeamMembers.ItemsSource = AllTeamMembers;
            listBoxTeamMembers.DisplayMemberPath = "Name";
            comboBoxTeamMembers.ItemsSource = AllUsers;
            comboBoxTeamMembers.DisplayMemberPath = "Name";
            Team = new Team();
            gridEditTeam.DataContext = Team;
            comboBoxTeamRegions.ItemsSource = AllSchoolRegions;
            comboBoxTeamRegions.DisplayMemberPath = "Name";
            comboBoxTeamLeader.ItemsSource = AllUsers;
            comboBoxTeamLeader.DisplayMemberPath = "Name";
            _adminService.FindAllTeamsCompleted += (s, ea) =>
                {
                    AllTeams.Clear();
                    foreach (var item in ea.Result)
                    {
                        AllTeams.Add(item);
                    }
                };

            _adminService.FindAllTeamsAsync();

            _adminService.UpdateTeamCompleted += (s, ea) =>
                {
                    var userids = new ObservableCollection<int>();
                    foreach (var item in AllTeamMembers)
                    {
                        userids.Add(item.Id);
                    }
                    //_adminService.ChangeTeamMembersAsync(Team.Id, userids);
                    ClearTeamData();
                };
            _adminService.AddTeamCompleted += (s, ea) =>
                {
                    var userids = new ObservableCollection<int>();
                    foreach (var item in AllTeamMembers)
                    {
                        userids.Add(item.Id);
                    }
                    //_adminService.ChangeTeamMembersAsync(Team.Id, userids);
                    ClearTeamData();
                };
            _adminService.DeleteTeamCompleted += (s, ea) =>
                {
                    ClearTeamData();
                };

            //_adminService.ChangeTeamMembersCompleted += (s, ea) =>
            //    {
            //        _adminService.FindAllTeamsAsync();
            //        AllTeamMembers.Clear();
            //        Team = new Team();
            //        this.gridEditTeam.DataContext = Team;
            //        comboBoxTeamRegions.SelectedIndex = -1;
            //        comboBoxTeamLeader.SelectedIndex = -1;
            //        comboBoxTeamLeader.SelectedIndex = -1;
            //        comboBoxTeamMembers.SelectedIndex = -1;
            //        comboBoxTeamRegions.SelectedIndex = -1;
            //    };

            #endregion

            _adminService.DeleteUserCompleted += (s, ea) =>
            {
                _adminService.GetAllUsersAsync();
            };
            this.listBoxUserRoles.DataContext = Roles;
            this.listBoxUserRoles.DisplayMemberPath = "RoleType";
            this.comboBoxRoles.ItemsSource = AllRoles;
            this.comboBoxRoles.DisplayMemberPath = "RoleType";
            _adminService.FindAllRolesCompleted += (s, ea) =>
            {
                foreach (var item in ea.Result)
                {
                    AllRoles.Add(item);
                }
            };
            this.listBox1.ItemsSource = AllUsers;
            this.listBox1.DisplayMemberPath = "Name";
            _adminService.AddUserCompleted += (s, ea) =>
            {
                OnAddUserCompleted(ea);
            };
            _adminService.GetAllUsersCompleted += (s, ea) =>
            {
                var selectedItem = this.listBox1.SelectedItem;
                AllUsers.Clear();
                foreach (var item in ea.Result)
                {
                    AllUsers.Add(item);
                }

                this.listBox1.SelectedItem = selectedItem;
            };

            _adminService.GetAllUsersAsync();
            _adminService.FindAllRolesAsync();



            _adminService.CreateRegionCompleted += (s, ea) =>
                                                       {
                newRegion.Id = ea.Result;
                listBoxRegions.Items.Add(newRegion);
                newRegion = new Region();
                textBoxNewRegion.Text = "";
                _adminService.FindAllRegionsAsync();
            };

            _adminService.FindAllRegionsCompleted += (s, ea) =>
            {
                listBoxRegions.Items.Clear();
                AllSchoolRegions.Clear();
                foreach (var region in ea.Result)
                {
                    listBoxRegions.Items.Add(region);
                    AllSchoolRegions.Add(region);
                }
            };

            _adminService.FindAllRegionsAsync();

            _adminService.FindAllSchoolsCompleted += (s, ea) =>
            {
                AllSchools.Clear();
                buttonCreateSchool_Click(null,null);
                foreach (var school in ea.Result)
                {
                    AllSchools.Add(school);
                }
            };
            _adminService.FindAllSchoolsAsync();

            _adminService.DeleteSchoolCompleted += (s, ea) => _adminService.FindAllSchoolsAsync();

            _adminService.SaveSchoolCompleted += (s, ea) => _adminService.FindAllSchoolsAsync();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnAddUser_Click(object sender, RoutedEventArgs e)
        {
            _adminService.AddUserAsync(User,Roles);
        }

        private void OnAddUserCompleted(AddUserCompletedEventArgs ea)
        {
            if (ea.Error == null)
            {
                    _adminService.GetAllUsersAsync();
                MessageBox.Show("User saved succesfully");
            }
            else
            {
                MessageBox.Show("Failed saving user");
            }
        }

        private void txtBoxPhone_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                return; //Added to handle TAB key
            }
            var thisKeyStr = "";
            if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
            {
                thisKeyStr = ".";
            }
            else
            {
                thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
            }
            var s = (sender as TextBox).Text + thisKeyStr;
            var rStr = "^[0-9]+[.]?[0-9]*$";
            var r = new Regex(rStr, RegexOptions.IgnoreCase);
            e.Handled = !r.IsMatch(s) || string.IsNullOrEmpty(thisKeyStr);

        }

      

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                User = (User) e.AddedItems[0];
                this.gridAddUser.DataContext = User;
                Roles.Clear();
                if(User.UserRole!=null)
                    foreach (var userRole in User.UserRole)
                    {
                        Roles.Add(userRole.Role);
                    }
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var user = new User();
            this.gridAddUser.DataContext = user;
            Roles.Clear();
            User = user;
            listBox1.SelectedIndex = -1;
        }

        private void buttonAddRole_Click(object sender, RoutedEventArgs e)
        {
            var role = ((Role)this.comboBoxRoles.SelectedItem);
            bool exists = this.listBoxUserRoles.Items.Cast<Role>().Any( r =>r.Id.Equals(role.Id));
            
            if(!exists)
            {
                Roles.Add(role);
            }

        }

        private void buttonRemoveRole_Click(object sender, RoutedEventArgs e)
        {
            var role = listBoxUserRoles.SelectedItem as Role;
            Roles.Remove(role);
        }

        private void buttonDeleteUser_Click(object sender, RoutedEventArgs e)
        {
            _adminService.DeleteUserAsync(User.Id);
        }

        private void tabSchools_GotFocus(object sender, RoutedEventArgs e)
        {
            
        }


        private Region newRegion;

        private void buttonCreateRegion_Click(object sender, RoutedEventArgs e)
        {
            var regionName = this.textBoxNewRegion.Text;
            newRegion = new Region();
            newRegion.Name = regionName;
            _adminService.CreateRegionAsync(newRegion);
        }

        private void buttonDeleteRegion_Click(object sender, RoutedEventArgs e)
        {
            _adminService.DeleteRegionAsync((Region) listBoxRegions.SelectedItem);
            listBoxRegions.Items.Remove(listBoxRegions.SelectedItem);
        }

        private void buttonCreateSchool_Click(object sender, RoutedEventArgs e)
        {
            School=new School();
            grid2.DataContext = School;
            comboBoxSchoolRegionName.SelectedItem = null;
        }

        private void buttonDeleteSchool_Click(object sender, RoutedEventArgs e)
        {
            _adminService.DeleteSchoolAsync(School);
        }

        private void listBoxSchools_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
                School = (School) listBoxSchools.SelectedItem;
                
                grid2.DataContext = School;
                if (School != null)
                {
                    SchoolRegion = School.Region;
                    comboBoxSchoolRegionName.SelectedItem = SchoolRegion == null
                                                                ? null
                                                                : (from region in
                                                                       comboBoxSchoolRegionName.Items.Cast<Region>()
                                                                   where region.Id == SchoolRegion.Id
                                                                   select region).First();
                }
            
        }

        private void buttonSaveSchool_Click(object sender, RoutedEventArgs e)
        {
            School.Region= null;
            _adminService.SaveSchoolAsync(School,SchoolRegion.Id);
        }

        private void comboBoxSchoolRegionName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SchoolRegion = (Region) comboBoxSchoolRegionName.SelectedItem;
        }

        private void listBoxTeams_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Team = (Team)listBoxTeams.SelectedItem;

            gridEditTeam.DataContext = Team;
            if (Team != null)
            {
                comboBoxTeamRegions.SelectedIndex = -1;
                if (Team.Regions != null && Team.Regions.Count > 0)
                {
                    for (int i = 0; i < comboBoxTeamRegions.Items.Count; i++)
                    {

                        if ((comboBoxTeamRegions.Items[i] as Region).Id == Team.Regions.First().Id)
                        {
                            comboBoxTeamRegions.SelectedIndex = i;
                            TeamRegion = (comboBoxTeamRegions.Items[i] as Region);
                            break;
                        }
                    }
                }

                for (int i = 0; i < comboBoxTeamLeader.Items.Count; i++)
                {
                    if ((comboBoxTeamLeader.Items[i] as User).Id == Team.TeamLeaderId)
                    {
                        comboBoxTeamLeader.SelectedIndex = i;
                        break;
                    }
                }

                //comboBoxTeamLeader.SelectedItem = comboBoxTeamLeader.Items.Cast<User>().First(u => u.Id == Team.TeamLeaderId);

                AllTeamMembers.Clear();
                foreach (var item in Team.TeamMember)
                {
                    AllTeamMembers.Add(item.User);
                }
            }
        }

        private void comboBoxTeamLeader_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var teamLeader = comboBoxTeamLeader.SelectedItem as User;
            if (teamLeader != null)
            {
                Team.TeamLeaderId = teamLeader.Id;
            }
        }

        private void buttonCreateTeam_Click(object sender, RoutedEventArgs e)
        {
            Team = new Team();
            AllTeamMembers.Clear();
            this.gridEditTeam.DataContext = Team;
            comboBoxTeamRegions.SelectedIndex = -1;
            comboBoxTeamLeader.SelectedIndex = -1;
            comboBoxTeamLeader.SelectedIndex = -1;
            comboBoxTeamMembers.SelectedIndex = -1;
            comboBoxTeamRegions.SelectedIndex = -1;
        }

        private void buttonSaveTeam_Click(object sender, RoutedEventArgs e)
        {
            int? TeamRegionId = null;
            if (TeamRegion != null)
            {
                TeamRegionId = TeamRegion.Id;
            }
            var useriIds = new ObservableCollection<int>();
            foreach (var item in AllTeamMembers)
            {
                useriIds.Add(item.Id);
            }
            if (Team.Id == 0)
            {
                _adminService.AddTeamAsync(Team, TeamRegionId, useriIds);
            }
            else
            {
                _adminService.UpdateTeamAsync(Team.Id, Team.Name, TeamRegionId, Team.TeamLeaderId, useriIds);
            }
        }

        private void buttonDeleteTeam_Click(object sender, RoutedEventArgs e)
        {
            _adminService.DeleteTeamAsync(Team.Id);
        }

        private void comboBoxTeamRegions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TeamRegion = (comboBoxTeamRegions.SelectedItem as Region);
        }

        private void buttonAddTeamMember_Click(object sender, RoutedEventArgs e)
        {
            var user = ((User)this.comboBoxTeamMembers.SelectedItem);
            bool exists = this.listBoxTeamMembers.Items.Cast<User>().Any(u => u.Id.Equals(user.Id));

            if (!exists)
            {
                AllTeamMembers.Add(user);
            }
        }

        private void buttonRemoveTeamMember_Click(object sender, RoutedEventArgs e)
        {
            var user = ((User)this.listBoxTeamMembers.SelectedItem);
            AllTeamMembers.Remove(user);
        }

        private void ClearTeamData()
        {
            _adminService.FindAllTeamsAsync();
            AllTeamMembers.Clear();
            Team = new Team();
            this.gridEditTeam.DataContext = Team;
            comboBoxTeamRegions.SelectedIndex = -1;
            comboBoxTeamLeader.SelectedIndex = -1;
            comboBoxTeamLeader.SelectedIndex = -1;
            comboBoxTeamMembers.SelectedIndex = -1;
            comboBoxTeamRegions.SelectedIndex = -1;
        }
    }
}
